package com.redlight.token;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @author chao
 * @Title: JwtHelper
 * @date 2019-01-24 21:26
 */
public class JwtHelper {
    public JwtHelper() {
    }

    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            Claims claims = (Claims) Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(base64Security)).parseClaimsJws(jsonWebToken).getBody();
            if (null != claims) {
                ;
            }

            return claims;
        } catch (Exception var3) {
            return null;
        }
    }

    public static String createJWT(String userId, String name, String issuer, String audience, long TTLMillis, String base64Security) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT").setId(userId).setSubject(name).setIssuer(issuer).setAudience(audience).signWith(signatureAlgorithm, signingKey);
        if (TTLMillis >= 0L) {
            long nowMillis = System.currentTimeMillis();
            long expMillis = nowMillis + TTLMillis * 1000L;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(new Date(nowMillis));
        }

        return builder.compact();
    }

    public static void main(String[] args) {
        String tokenType = "Bearer";
        String userId = "123";
        String name = "SuperAdmin";
        String token = createJWT(userId, name, "admin", "Admin JWT Online", 0L, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9");
        System.out.println("生成的Token：" + tokenType + " " + token);
    }
}
